package com.shanjupay.paymentagent.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.github.binarywang.wxpay.util.SignUtils;
import com.github.wxpay.sdk.WXPay;
import com.shanjupay.paymentagent.config.AlipayConfig;
import com.shanjupay.paymentagent.config.MyWXPayconfig;
import com.shanjupay.paymentagent.service.EchoService;
import com.shanjupay.paymentagent.util.vx.WxApiClient;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class TestPayController {


    @RequestMapping("/alipay")
    public String alipay(HttpServletRequest request, HttpServletResponse response){

        String out_trade_no = "12";
        // 订单名称，必填
        String subject = "测试1订单";
        System.out.println(subject);
        // 付款金额，必填
        String total_amount="0.01";
        // 商品描述，可空
        String body = "商品描述1";
        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY1";

        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            System.out.println(form);
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }






    @RequestMapping("/wxpay")
    public String wxpay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String out_trade_no = "2111111126";
        // 订单名称，必填
        String subject = "测试1订单";
        System.out.println(subject);
        // 付款金额，必填
        String total_amount="1";
        // 商品描述，可空
        String body = "商品描述1";

        MyWXPayconfig config = new MyWXPayconfig();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", total_amount);
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", wxNotifyUrl);
        data.put("trade_type", "MWEB");  // 此处指定为扫码支付 NATIVE JSAPI MWEB
        data.put("product_id", "12");

        String url="";
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            url = resp.get("mweb_url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write("<a href='"+url+"'>aaaa</a>");//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return "redirect:"+url;

        return null;
    }


    public static String webUrl = "http://xfc.nat300.top/payment-receiver";

    public static String oauth2RequestUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";

    public static String oauth2CodeReturnUrl = "http://xfc.nat300.top/payment-receiver/wx-oauth-code-return";

    public static String wxJsPayUrl = "http://xfc.nat300.top/payment-receiver/wxjspay";

    public static String wxNotifyUrl = webUrl + "/wxpay-notify";//网关外地址


    @RequestMapping("/wx-oauth-code")
    public String wxOAuth2Code(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("进入wx-oauth-code");

        MyWXPayconfig config = new MyWXPayconfig();
        String url = String.format("%s?appid=%s&scope=snsapi_base&state=test&redirect_uri=%s",oauth2RequestUrl, config.getAppID(), URLEncoder.encode(oauth2CodeReturnUrl,"utf-8"));

        return "redirect:" + url;
    }

    @RequestMapping("/wx-oauth-code-return")
    public String wxOAuth2CodeReturn(HttpServletRequest request, HttpServletResponse response){
        System.out.println("进入wx-oauth-code-return");
        String requestURI = request.getRequestURI();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        System.out.print(requestURI + ": \n" + params.toString());


        String code = request.getParameter("code");
        String openId = "";
        try {
            MyWXPayconfig config = new MyWXPayconfig();
            openId = WxApiClient.getOAuthOpenId(config.getAppID(), config.getAppSecret(), code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:" + wxJsPayUrl + "?openid=" + openId ;
    }


    @RequestMapping("/wxjspay")
    public ModelAndView wxjspay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("进入wxjspay");
        String out_trade_no = "1111111133";
        // 订单名称，必填
        String subject = "测试1订单";
        System.out.println(subject);
        // 付款金额，必填
        String total_amount="1";
        // 商品描述，可空
        String body = "商品描述1";

        MyWXPayconfig config = new MyWXPayconfig();
        WXPay wxpay = new WXPay(config);

        String openId = request.getParameter("openid");

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", total_amount);
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", wxNotifyUrl);
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付 NATIVE JSAPI MWEB
        data.put("openid",openId);
        data.put("product_id", "12");

        String url="";
        Map<String, String> rst = new HashMap<>();
        try {


            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);

            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String nonceStr = String.valueOf(System.currentTimeMillis());
            rst.put("appId",resp.get("appid"));
            rst.put("timeStamp",timestamp);
            rst.put("nonceStr",nonceStr);
            rst.put("package","prepay_id=" + resp.get("prepay_id"));
            rst.put("signType","HMAC-SHA256");
            rst.put("paySign", SignUtils.createSign(rst,config.getKey(),"HMAC-SHA256"));


        } catch (Exception e) {
            e.printStackTrace();
        }


        return new ModelAndView("jspay",rst);
    }



}
